<template>
  <div>
    <div class="panel panel-default my-panel">
      <div class="panel-heading panel-title">
        <h1>ToDoList</h1>
      </div>
      <div class="panel-body">
        <div class="row">
          <ToDoHeader @addToDo="addToDo"/>
        </div>
        <div class="row">
          <ToDoBody :todos="todos" @complete="complete"/>
        </div>
        <div class="row">
          <!-- 使用PubSub发布订阅不需要在这里绑定checkAll事件 -->
          <ToDoFooter :finish="finish" :all="todos.length" :checked="checked" @deleteChecked="deleteChecked"/>
          <!-- <ToDoFooter :finish="finish" :all="todos.length" @checkAll="checkAll" :checked="checked" @deleteChecked="deleteChecked"/> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import ToDoBody from '@/components/ToDoList/ToDoBody'
import ToDoHeader from '@/components/ToDoList/ToDoHeader'
import ToDoFooter from '@/components/ToDoList/ToDoFooter'
import storageUtil from '@/utils/storageUtil'
export default {
  components: {
    ToDoBody, ToDoHeader, ToDoFooter
  },
  data () {
    return {
      // todos: [
      //   {text: '吃饭', state: true},
      //   {text: '睡觉', state: false},
      //   {text: '喝水', state: true},
      //   {text: '打豆豆', state: false}
      // ],
      todos: storageUtil.readTodos(),
      checked: false
    }
  },
  mounted () {
    // 所有的回调函数都用箭头函数
    // 订阅消息 在这里绑定
    PubSub.subscribe('checkAll', (msg, data) => {
      console.log(msg)
      this.checkAll()
    })
  },
  // 为了缓存todos，深度监视todos的变化，一旦变化就存入缓存
  watch: {
    todos: {
      deep: true, // 深度监视
      // handler: function (value) {
      //   storageUtil.saveTodos(value)
      // }
      // 简写 给handler一个回调函数 把函数名写在这里
      handler: storageUtil.saveTodos
    }
  },
  computed: {
    finish () {
      let count = 0
      this.todos.forEach(item => {
        if (item.state) {
          count++
        }
      })
      return count
    }
  },
  methods: {
    addToDo (value) {
      this.todos.unshift(value)
    },
    complete (index) {
      // 这样是改不掉的
      this.todos[index].state = !this.todos[index].state
      console.log(this.todos[index].state)
    },
    checkAll () {
      this.todos.forEach(item => {
        item.state = !this.checked
      })
      this.checked = !this.checked
    },
    deleteChecked () {
      const {todos} = this
      const n = todos.length
      for (let i = 0; i < n; i++) {
        if (todos[i] && todos[i].state === true) {
          todos.splice(i, 1)
          i--
        }
      }
    }
  }
}
</script>

<style>
.my-panel {
  margin: 0 auto;
  width: 1000px;
}
.row {
  padding: 15px;
}
</style>
